<template>
    <div>
        <el-dialog :visible.sync="dialogVisible" width="600px"   center>
            <!-- :before-close="handleClose" -->
            <span class="el-dialog__title" slot="title">用户注册</span>
            <!-- model:模型值
                 from:拿到表单
                 rules:校验规则
             -->
            <el-form
                :model="form"
                ref="form"
                :rules="rules"
                label-width="80px"
                label-position="left"
            >
                <el-form-item label="头像" prop="avatar">
                    <!-- action 上传的头像地址 跟axios无关
                    data:上传时候需要传递的额外参数,我们现在后需要传递(他的值事宜个对象,对象属于加image,这是后台规定的,值是file类型,也是后台规定的)
                    show-file-list: 是否展示上传之后的列表
                    on-success:上传成功之后的回调,做两件事,预览和给from.avatar 
                    on-error :上传失败的回调,给他一个展示 
                    beforre-upload: 上传之前的回调,可以在这这里检测类型和大小,还可以给额外参数赋值
                     -->
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :data="uploadData"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleAvatarError"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="昵称" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" show-password></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="图形码" prop="code">
                            <el-input v-model="form.code"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col style="margin-left: 10px" :span="7">
                        <img
                            :src="registerCodeURL"
                            style="width: 100%; height: 40px"
                            @click="changeRegisterCodeURL"
                        />
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="验证码" prop="rcode">
                            <el-input v-model="form.rcode"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col style="margin-left: 10px" :span="7">
                        <el-button size="default" @click="getRcode"
                            >获取用户验证码</el-button
                        >
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="register">确定注册</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            dialogVisible: false,
            registerCodeURL: `${process.env.VUE_APP_BASEURL}/captcha?type=sendsms`,
            imageUrl: "",//上传之后的图片地址
            uploadUrl: `${process.env.VUE_APP_BASEURL}/uploads`,
            uploadData: {
                // 上传时候的额外参数
                image: null,
            },
            form: {
                // 里面的值将来是要提交给后台的，看接口文档
                avatar: "", // 头像地址
                username: "", // 昵称
                email: "", // 邮箱
                phone: "", // 手机
                password: "", // 密码
                code: "", // 图像码
                rcode: "", // 验证码
            },
            rules: {
                avatar: [
                    {
                        required: true,
                        message: "昵称不能为空",
                        trigger: "change",
                    },
                ],
                username: [
                    {
                        required: true,
                        message: "昵称不能为空",
                        trigger: "blur",
                    },
                ],
                email: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            //rule 校验规则
                            // value:用户输入的值
                            // callback效验是否成功都需要调用
                            if (!value) {
                                return callback(new Error("邮箱不能为空"));
                            }
                            // 利用邮箱的正则去进行匹配
                            // eslint禁用
                            /* eslint-disable */
                            const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
                            if (!reg.test(value)) {
                                return callback(new Error("邮箱不正确"));
                            }
                            callback();
                        },
                        trigger: "blur",
                    },
                ],
                phone: [
                    {
                        required: true,
                        // validator 是校验器
                        validator: (rule, value, callback) => {
                            // rule 检验对象、value 输入的值 callback 校验成功还是失败的【一定要调用】
                            if (!value) {
                                return callback(new Error("手机号不能为空"));
                            }

                            // 手机的正则校验
                            const reg = /^1[3-9][0-9]{9}$/;
                            if (!reg.test(value)) {
                                return callback(new Error("手机号不合法"));
                            }

                            // 校验成功不需要加任何参数，但是一定要调用
                            callback();
                        },
                        trigger: "blur",
                    },
                ],
                password: [
                    {
                        required: true,
                        message: "密码不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 6,
                        max: 16,
                        message: "密码必须在6-16位之间",
                        trigger: "blur",
                    },
                ],
                code: [
                    {
                        required: true,
                        message: "图形码不能为空",
                        trigger: "blur",
                    },
                ],
                rcode: [
                    {
                        required: true,
                        message: "验证码不能为空",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    methods: {
        changeRegisterCodeURL() {
            this.registerCodeURL = `${
                process.env.VUE_APP_BASEURL
            }/captcha?type=sendsms&t=${new Date() - 0}`;
        },

        //获取验证码
        async getRcode() {
            // 判断用户是否输入了手机号 和验证码

            let isOk = 0;
            this.$refs.form.validateField(["phone"], (errorMessage) => {
                if (!errorMessage) {
                    isOk++;
                }
            });
            this.$refs.form.validateField(["code"], (errorMessage) => {
                if (!errorMessage) {
                    isOk++;
                }
            });
            if (isOk === 2) {
                const res = await this.$axios.post("/sendsms", {
                    phone: this.form.phone,
                    code: this.form.code,
                });
                console.log(res);
                if (res.code === 200) {
                    this.form.rcode = res.data.captcha;
                } else {
                    this.changeRegisterCodeURL();
                    this.$message.error(res.message);
                }
            }
        },

        // 上传图像成功的回调
        handleAvatarSuccess(res, file) {
            console.log(res);
            if (res.code === 200) {

            //实现预览功能
               this.imageUrl = URL.createObjectURL(file.raw);
                console.log('我进来了');
                //给this.form.avatar  赋值
                this.form.avatar = res.data.file_path;
            }else{
                this.$message.error(res.message);
            }
        },
        // 上传头像失败的回调
        handleAvatarError(err){
            console.log(err);
            this.$message.error("上传失败");
        },
        //上传头像之前的回调  (file)  文件格式
        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" ||
                file.type === "image/png" ||
                file.type === "image/gif";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG//png/gif 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            console.log(file);
            // 给需要传递的额外参数赋值
            this.uploadData.image = file;
            return isJPG && isLt2M;
        },
        register(){
            //先判断效验里面是否都有内容
            this.$refs.form.validate(async (valid)=>{
                if (!valid) return; 
                let res = await this.$axios.post('/register',this.form);
                console.log(res);
                if(res.code === 200 ){
                    this.$message.success('注册成功');
                    this.dialogVisible = false;
                    
                }else{
                    this.$message.error(res.message);
                    this.changeRegisterCodeURL();
                }
                
             }
            )
        },
      
    },
    watch:{
        dialogVisible(value){
        //    this.$refs.form.resetFields();
           if(!value){
               this.$refs.form.resetFields();
               this.imageUrl='';
           }
        }
    }
};
</script>
<style lang="less">

.avatar-uploader {
    display: flex;
    justify-content: center;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>